package cn.szzsi._admin;

import cn.szzsi._Config;
import cn.szzsi.common.bean.ProductImage;
import cn.szzsi.common.bean.SystemConfig;
import cn.szzsi.common.kit.CommonUtil;
import cn.szzsi.common.kit.ModelUtils;
import cn.szzsi.common.model.*;
import cn.szzsi.common.model.zshop.CompanyInfo;
import cn.szzsi.service.HtmlService;
import cn.szzsi.service.ProductImageService;
import cn.szzsi.service.ProductService;
import cn.szzsi.validator.BusinessProductValidator;
import com.jfinal.aop.Before;
import com.jfinal.kit.JsonKit;
import com.jfinal.kit.Ret;
import com.jfinal.kit.StrKit;
import com.jfinal.plugin.activerecord.Page;
import com.jfinal.plugin.activerecord.tx.Tx;
import com.jfinal.upload.UploadFile;
import org.apache.commons.lang3.ArrayUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.math.NumberUtils;

import java.io.File;
import java.math.BigDecimal;
import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * 商户后台类 - 商品
 *
 */
public class ProductController extends BaseAdminController<Product> {
    private List<UploadFile> productImages;//List<UploadFile>---List是集合，<UploadFile>是泛型，规定List中存储UploadFile类型的数据
    private String[] productImageParameterTypes;//String[] arr = {"1","2","3"};
    private String[] productImageIds;
    private String shopId;
    private Product product = new Product();
    Map<String, String> productAttributeMap = new HashMap<String, String>();//以键值对的形式存储数据
    // 列表
    public void list() {
        render("product_list.html");
    }
    //ajax product list
    public void ajaxlist(){
        shopId=getAttr("shopId");
        SiteConfig siteConfig = SiteConfig.getByShopId(shopId);
        String userId=getAttr("userId");
        String sql = "select p.*,pc.name as categoryName  from mall_product p left join mall_product_category pc on p.productCategory_id = pc.id  where p.uid = ? and display=1 order by modifyDate desc,createDate desc";
        if (siteConfig.getProductRank() == 1 && !shopId.equals(userId)) {
            sql = "select p.*,pc.name as categoryName  from mall_product p left join mall_product_category pc on p.productCategory_id = pc.id  where p.uid = ? and p.creator='"+getAttrForStr("userId")+"'  and display=1 order by modifyDate desc,createDate desc";
        }
        List<Product> lists = Product.dao.find(sql,shopId);
        for(Product p:lists){
            p.initParams();
        }
        renderJson(lists);
    }
    // 添加
    public void add() {
        shopId=getAttr("shopId");
        //setAttr("productCategoryTreeList", getProductCategoryTreeList());//商户的商品分类

        //上面代码注释,由原来的商户自己可以添加分类,改为平台给商户添加
        CompanyInfo companyInfo=CompanyInfo.dao.getByShopId(shopId);
        String productCategoryId=companyInfo.getProductCategoryId();
        List<ProductCategory> productCategoryTreeList=null;
        if(productCategoryId!=null){
            String productCategoryIdArry[]=productCategoryId.split(",");
            String ids="";
            for(int i=0;i<productCategoryIdArry.length;i++){
                ids+= JsonKit.toJson(productCategoryIdArry[i])+",";
            }
            if(ids.endsWith(",")){
                ids= ids.substring(0,ids.length()-1);
            }
            productCategoryTreeList=ProductCategory.dao.find("select * from mall_product_category where id in ("+ids+")");
            setAttr("productCategoryTreeList", productCategoryTreeList);
        }else{
            setAttr("productCategoryTreeList", productCategoryTreeList);
        }
        //上面代码注释,由原来的商户自己可以添加分类,改为平台给商户添加

        setAttr("allBrand", getAllBrand());//商户的品牌
        setAttr("allWeightUnit", getAllWeightUnit());
        setAttr("allProductType", getAllProductType());
        //获取所有规格和规格值
        setAttr("allSpecification", Specification.me.getAllByCategoryIdAndShopId(null,shopId));
        setAttr("shopId",shopId);
        render("product_input.html");
    }
    public void getProduct() {

        String select = "select * ";
        String sqlExceptSelect = " from mall_product ";

        Page<Product> product = Product.dao.paginate(1, 20, select, sqlExceptSelect);
        Map<String, Object> map = new HashMap<String, Object>();
        map.put("page", product.getPageNumber());
        map.put("total", product.getTotalPage());
        map.put("records", product.getTotalRow());
        map.put("rows", product.getList());
        renderJson(map);
    }

    public void findProduct() {
        // 获取请求次数
        int draw = getParaToInt("draw", 0);
        // 数据起始位置
        int start = getParaToInt("start", 0);
        // 数据长度
        int pageSize = getParaToInt("length", 10);
        // 页码
        int pageNumber = 1;

        if (0 < start) {
            pageNumber = (start / pageSize) + 1;
        }
        //定义列名
        String[] cols = {"productSn", "name", "price", "isMarketable", "isBest", "isNew", "isHot", "store", "modifyDate"};

        //获取客户端需要那一列排序
        int orderColumn = getParaToInt("order[0][column]", 0);
        String orderName = cols[orderColumn];

        //获取排序方式 默认为asc
        String orderDir = getPara("order[0][dir]", "asc");

        //获取用户过滤框里的字符
        String searchValue = getPara("search[value]", "");

        String select = "select * ";
        String sqlExceptSelect = " from mall_product ";

        // 全局搜索
        if (StrKit.notBlank(searchValue)) {
            sqlExceptSelect += " where ";
            List<String> sArray = new ArrayList<String>();
            for (String col : cols) {
                sArray.add(col + " like '%" + searchValue + "%'");
            }

            for (int i = 0; i < sArray.size() - 1; i++) {
                sqlExceptSelect += sArray.get(i) + " or ";
            }
            sqlExceptSelect += sArray.get(sArray.size() - 1);
        }

        // 排序
        if (StrKit.notBlank(orderName) && StrKit.notBlank(orderDir)) {
            sqlExceptSelect += " order by " + orderName + " " + orderDir; // 排序
        } else {
            sqlExceptSelect += " order by createDate desc "; // 默认排序
        }

        Page<Product> product = Product.dao.paginate(pageNumber, pageSize, select, sqlExceptSelect);
        Map<String, Object> map = new HashMap<String, Object>();
        map.put("draw", draw);
        map.put("data", product.getList());
        map.put("recordsFiltered", product.getTotalRow());  //过滤后记录数
        map.put("recordsTotal", product.getTotalRow()); //总记录数
        renderJson(map);
    }

    // 编辑
    public void edit() {
        shopId=getAttr("shopId");
        String id = getPara("id","");
        product = Product.dao.findById(id);
        if(StrKit.notBlank(id)){
            setAttr("product", Product.dao.findById(id));
        }
        //setAttr("productCategoryTreeList", getProductCategoryTreeList());
        //上面代码注释,由原来的商户自己可以添加分类,改为平台给商户添加
        CompanyInfo companyInfo=CompanyInfo.dao.getByShopId(shopId);
        String productCategoryId=companyInfo.getProductCategoryId();
        if(StrKit.notBlank(productCategoryId)){
            String productCategoryIdArry[]=productCategoryId.split(",");
            String ids="";
            for(int i=0;i<productCategoryIdArry.length;i++){
                ids+= JsonKit.toJson(productCategoryIdArry[i])+",";
            }
            if(ids.endsWith(",")){
                ids= ids.substring(0,ids.length()-1);
                List<ProductCategory> productCategoryTreeList=ProductCategory.dao.find("select * from mall_product_category where id in ("+ids+")");
                setAttr("productCategoryTreeList", productCategoryTreeList);
            }
        }

        //上面代码注释,由原来的商户自己可以添加分类,改为平台给商户添加

        setAttr("allBrand", getAllBrand());
        setAttr("allWeightUnit", getAllWeightUnit());
        setAttr("allProductType", getAllProductType());
        //获取所有规格和规格值
        setAttr("allSpecification", Specification.me.getAllByCategoryIdAndShopId(null,shopId));
        //获取本系列所有的规格和规格值
        setAttr("specificationTypes", ProductService.service.getAllProductSpecificationType(product));
        setAttr("shopId",shopId);
        render("product_edit.html");
    }
    public void updateBlur(){
        String id = getPara("id","");
        Integer order = getParaToInt("order",0);
        Product product= Product.dao.findById(id);
        product.setSortNo(order);
        product.update();
        renderJson(Ret.ok());
    }

    public void updatePrice(){
        String id = getPara("id","");
        String priceStr = getPara("price");
        if (StringUtils.isNotBlank(priceStr) && NumberUtils.isNumber(priceStr)) {
            BigDecimal price = new BigDecimal(priceStr);
            Product product= Product.dao.findById(id);
            product.setPrice(price);
            product.update();
        }
        renderJson(Ret.ok());
    }

    public void updateStore(){
        String id = getPara("id","");
        String storeStr = getPara("store");
        if (StringUtils.isNotBlank(storeStr) && NumberUtils.isNumber(storeStr)) {
            Product product= Product.dao.findById(id);
            Integer freezeStore = product.getFreezeStore() == null ? 0 : product.getFreezeStore();
            product.setStore(freezeStore + Integer.parseInt(storeStr));
            product.update();
        }
        renderJson(Ret.ok());
    }


    // 保存
    @Before({BusinessProductValidator.class, Tx.class})
    public void save() {
        shopId=getAttr("shopId");
        String userId=getAttrForStr("userId");
        productImages = getFiles();
        if(productImages.size()<=0){
            renderJson(Ret.fail("info","请上传商品图片!"));
            return;
        }else if(productImages.size()>5){
            renderJson(Ret.fail("info","商品图片不允许超过5张!"));
            return;
        }
        product = getModel(Product.class);
        product.set("uid",shopId);
        product.setCreator(userId);
        product.setChecked("0");
        String weightUnit = getPara("weightUnit","");

        if (StrKit.notBlank(weightUnit)){
            product.set("weightUnit", Product.WeightUnit.valueOf(weightUnit).ordinal());
        }
        if(StrKit.isBlank(product.getProductcategoryId())){
            renderJson(Ret.fail("info","商品分类不允许为空"));
            return;
        }
        if (product.getBigDecimal("price").compareTo(new BigDecimal("0")) <=0) {
            renderJson(Ret.fail("info","销售价不允许小于0!"));
            return;
        }
        if (product.getBigDecimal("marketPrice").compareTo(new BigDecimal("0")) <=0) {
            renderJson(Ret.fail("info","市场价不允许小于0!"));
            return;
        }
        if (product.getDouble("weight") < 0) {
            renderJson(Ret.fail("info","商品重量只允许为正数或零!"));
            return;
        }
        if (StrKit.notBlank(product.getProductSn())) {
            if (Product.dao.isExistProductSn(product)) {
                renderJson(Ret.fail("info","货号重复,请重新输入!"));
                return;
            }
        }
        if(StrKit.isBlank(product.getBackGroundImg())){
            renderJson(Ret.fail("info","请上传背景图!"));
            return;
        }

        if (getSystemConfig().getPointType() == SystemConfig.PointType.productSet) {
            product.set("point",0);
        } else {
            product.set("point",0);
        }

        // 处理上传的图片
        if (productImages != null && productImages.size() > 0) {
            String allowedUploadImageExtension = getSystemConfig().getAllowedUploadImageExtension().toLowerCase();
            if (StringUtils.isEmpty(allowedUploadImageExtension)) {
                renderJson(Ret.fail("info","不允许上传图片文件!"));
                return;
            }
            for(int i = 0; i < productImages.size(); i ++) {
                File images = productImages.get(i).getFile();
                String productImageExtension =  StringUtils.substringAfterLast(images.getName(), ".").toLowerCase();
                String[] imageExtensionArray = allowedUploadImageExtension.split(SystemConfig.EXTENSION_SEPARATOR);
                if (!ArrayUtils.contains(imageExtensionArray, productImageExtension)) {
                    renderJson(Ret.fail("info","只允许上传图片文件类型:"+allowedUploadImageExtension));
                    return;
                }
                if (getSystemConfig().getUploadLimit() != 0 && images.length()/1000 > 1000) {
                    renderJson(Ret.fail("info","上传商品图片大小超出限制,最大1M!"));
                    return;
                }
            }
        }

        List<ProductImage> productImageList = new ArrayList<ProductImage>();
        if (productImages != null && productImages.size() > 0) {
            for(int i = 0; i < productImages.size(); i ++) {
                ProductImage productImage = ProductImageService.service.buildProductImage(productImages.get(i).getFile(),shopId);
                productImageList.add(productImage);
            }
        }
        product.setProductImageList(productImageList);
        product.set("freezeStore",0);
        //保存产品规格
        ProductService.service.saveOrUpdateProductWithSpecification(product,getRequest(),shopId,userId);

        // 保存产品属性
        /*if (productAttributeMap != null && productAttributeMap.size() > 0) {
            product.setProductAttributeMap(productAttributeMap,shopId);
        }*/
        // 生成静态页面(先注释,暂时由平台审核通过后,自动生成)
        /*if (product.getBoolean("isMarketable")) {// 是否上架
            boolean isMobileDevice= CommonUtil.isMobileDevice(getRequest());//判断是pc访问还是wap访问
            String path= CommonUtil.getPathByUidAndType(shopId,isMobileDevice);//获取模板路径
            String shopAlias= SiteConfig.getByShopId(shopId).getStr("shopAlias");//获取店铺别名
            HtmlService.service.businessProductContentBuildHtml(product,isMobileDevice,path,shopAlias,shopId);
        }*/
        renderJson(Ret.ok("info","添加成功!").set("url","list"));
    }

    // 更新
    @SuppressWarnings("unused")
    @Before({BusinessProductValidator.class,Tx.class})
    public void update() {
        String userId=getAttrForStr("userId");
        productImages = getFiles();
        product = getModel(Product.class);
        product.setChecked("0");
        productImageIds = getParaValues("productImageIds");
        productImageParameterTypes = getParaValues("productImageParameterTypes");
        shopId=getAttr("shopId");
        String weightUnit = getPara("weightUnit","");
        if (StrKit.notBlank(weightUnit)){
            product.set("weightUnit", Product.WeightUnit.valueOf(weightUnit).ordinal());
        }
        if(StrKit.isBlank(product.getProductcategoryId())){
            renderJson(Ret.fail("info","商品分类不允许为空"));
            return;
        }
        if (product.getBigDecimal("price").compareTo(new BigDecimal("0")) <=0) {
            renderJson(Ret.fail("info","销售价不允许小于0!"));
            return;
        }
        if (product.getBigDecimal("marketPrice").compareTo(new BigDecimal("0")) <=0) {
            renderJson(Ret.fail("info","市场价不允许小于0!"));
            return;
        }
        if (product.getDouble("weight") < 0) {
            renderJson(Ret.fail("info","商品重量只允许为正数或零!"));
            return;
        }

        Product persistent = Product.dao.findById(product.getId());
        if (StrKit.notBlank(product.getProductSn())) {
            if (Product.dao.isExistProductSn(product)) {
                renderJson(Ret.fail("info","货号重复,请重新输入!"));
                return;
            }
        }

        if (productImages != null && productImages.size() > 0) {
            String allowedUploadImageExtension = getSystemConfig().getAllowedUploadImageExtension().toLowerCase();
            if (StringUtils.isEmpty(allowedUploadImageExtension)) {
                renderJson(Ret.fail("info","不允许上传图片文件"));
                return;
            }
            for(int i = 0; i < productImages.size(); i ++) {
                File images = productImages.get(i).getFile();
                String productImageExtension =  StringUtils.substringAfterLast(images.getName(), ".").toLowerCase();
                String[] imageExtensionArray = allowedUploadImageExtension.split(SystemConfig.EXTENSION_SEPARATOR);
                if (!ArrayUtils.contains(imageExtensionArray, productImageExtension)) {
                    renderJson(Ret.fail("info","只允许上传图片文件类型:"+allowedUploadImageExtension));
                    return;
                }
                /*if (getSystemConfig().getUploadLimit() != 0 && images.length() > getSystemConfig().getUploadLimit() * 1024) {
                    renderJson(Ret.fail("info","此上传文件大小超出限制"));
                    return;
                }*/
                if (getSystemConfig().getUploadLimit() != 0 && images.length()/1000 > 1000) {
                    renderJson(Ret.fail("info","上传商品图片大小超出限制,最大1M!"));
                    return;
                }
            }
        }

        List<ProductImage> productImageList = new ArrayList<ProductImage>();
        if (productImageParameterTypes != null && productImageParameterTypes.length > 0) {
            int index = 0;
            int productImageFileIndex = 0;
            int productImageIdIndex = 0;
            for (String parameterType : productImageParameterTypes) {
                if (StringUtils.equalsIgnoreCase(parameterType, "productImageFile")) {
                    ProductImage destProductImage = ProductImageService.service.buildProductImage(productImages.get(productImageFileIndex).getFile(),shopId);
                    productImageList.add(destProductImage);
                    productImageFileIndex ++;
                    index ++;
                } else if (StringUtils.equalsIgnoreCase(parameterType, "productImageId")) {
                    ProductImage destProductImage = persistent.getProductImage(productImageIds[productImageIdIndex]);
                    productImageList.add(destProductImage);
                    productImageIdIndex ++;
                    index ++;
                }
            }
        }
        if (product.getBrand()==null) {
            product.set("brand_id",null);
        }
        if (getSystemConfig().getPointType() == SystemConfig.PointType.productSet) {
            /*if (product.get("point") == null) {
                renderJson(Ret.fail("info","积分不允许为空"));
                return;
            }*/
        } else {
            product.set("point",0);
        }
        if (product.get("store") == null || product.getInt("store")==0) {
            product.set("freezeStore",0);
        } else {
            product.set("freezeStore",persistent.getInt("freezeStore"));

        }
        //

        product.set("store",product.getStore()+product.getFreezeStore());

        List<ProductImage> persistentProductImageList = persistent.getProductImageList();
        if (persistentProductImageList != null && persistentProductImageList.size() > 0) {
            for (ProductImage persistentProductImage : persistentProductImageList) {
                if (!productImageList.contains(persistentProductImage)) {
                    ProductImageService.service.deleteFile(persistentProductImage);
                }
            }
        }

        // 产品图片地址
        if (productImageList != null && productImageList.size() > 0) {
            product.setProductImageList(productImageList);
        }
        // 保存产品属性
        /*if (productAttributeMap != null && productAttributeMap.size() > 0) {
            product.setProductAttributeMap(productAttributeMap,shopId);
        }*/
        //修改产品的htmlFilePath(待改进,打算商品htmlFilePath去除shopAlias)
        String shopAlias= SiteConfig.getByShopId(shopId).getStr("shopAlias");//获取店铺别名S
        String htmlFilePath=product.getStr("htmlFilePath");
        htmlFilePath=htmlFilePath.replace("/shop","");
        int start=htmlFilePath.indexOf("/")+1;
        int end=htmlFilePath.indexOf("/",start);
        String target=htmlFilePath.substring(start,end);
        htmlFilePath=htmlFilePath.replace(target,shopAlias);
        product.set("htmlFilePath","/shop"+htmlFilePath);

        //保存产品规格
//        updated(product);
        ProductService.service.saveOrUpdateProductWithSpecification(product,getRequest(),shopId,userId);

        // 生成静态页面(覆盖原来静态页面) //先注释,暂时由平台审核通过后,自动生成
        /*if (product.getBoolean("isMarketable")) {// 是否上架
            boolean isMobileDevice= CommonUtil.isMobileDevice(getRequest());//判断是pc访问还是wap访问
            String path= CommonUtil.getPathByUidAndType(shopId,isMobileDevice);//获取模板路径
            String product_id=getPara("product_id");
            Product product= Product.dao.findById(product_id);
            HtmlService.service.businessProductContentBuildHtml(product,path,shopAlias,shopId);
        }*/

        //商品修改后,重新生成店铺首页,因为现在统一由超级后台审核通过后展示,所以该商品暂时不会展示
        _Config.fixedThreadPool.execute(new Runnable() {
            @Override
            public void run() {
                SiteConfig siteConfig= SiteConfig.getByShopId(product.getUid());
                HtmlService.service.indexBuildHtml(siteConfig);
            }
        });
        renderJson(Ret.ok("info","修改成功!").set("url","list"));
        //redirect("list");
    }

    // 删除
    @Override
    public void delete() {
        ids = getParaValues("ids");
        if (ids != null && ids.length > 0) {
                for (String id : ids) {
                Product product = Product.dao.findById(id);
                List<OrderItem> orderItemList = product.getOrderItemList();
                if (orderItemList != null && orderItemList.size() > 0) {
                    for (OrderItem orderItem : orderItemList) {
                        if(orderItem.getOrder()!=null) {
                            if (orderItem.getOrder().getOrderStatusValue() != Orders.OrderStatus.completed && orderItem.getOrder().getOrderStatusValue() != Orders.OrderStatus.invalid) {
                                renderJson(Ret.fail("info","商品[" + product.getStr("name") + "]订单处理未完成，删除失败！"));
                                return;
                            }
                        }
                    }
                }

                    //如果该商品下面存在其他sku,则提示用户先删除其他商品
                    if(product.getDisplay()){//展示在页面上的商品
                        String specificationtype=product.getSpecificationtype();
                        List<Product> products= Product.dao.getBySpecificationTypeAndDisplay(specificationtype,0);
                        if(products.size()>0){
                            renderJson(Ret.fail("info","请先将该商品下的sku删除!"));
                            return;
                        }
                    }
                if (Product.dao.delete(product)) {
                    renderJson(Ret.ok("info","删除成功"));
                } else {
                    renderJson(Ret.fail("info","删除失败"));
                }
            }
        }else {
            renderJson(Ret.fail("info","商品未选中，删除失败！"));
            //ajaxJsonErrorMessage("商品未选中，删除失败！");
        }

    }

    //礼物赠送
    public void addgift(){
        shopId=getAttr("shopId");
        String productId = getPara("id","");
        setAttr("shopId",shopId);
        setAttr("productId",productId);
        setAttr("productGifts", ProductGift.dao.getByProductId(productId));
        render("product_gift.html");
    }
    //礼物赠送
    public void savegift(){
        String productId = getPara("productId","");
        //保存产品礼物
        List<ProductGift> svl = ModelUtils.batchInjectModel(getRequest(),ProductGift.class,"productGift");
        for(ProductGift sv:svl){
            if(sv.getStr("id")!=null){
                sv.set("id",sv.getStr("id")).set("productId",productId).update();
            }else{
                sv.set("id", CommonUtil.getUUID()).set("productId",productId).set("createDate",new Date()).save();
            }
        }
        redirect("/mall/admin/product/list");
    }
    //删除礼物
    public void deletegift(){
        String id=getPara("id");
        ProductGift.dao.deleteById(id);
        ajaxJsonSuccessMessage("删除成功!");
    }


    // 获取所有商品类型
    public List<ProductType> getAllProductType() {
        shopId=getAttr("shopId");
        return ProductType.dao.getAllByShopId(shopId);
    }

    // 获取所有品牌
    public List<Brand> getAllBrand() {
        shopId=getAttr("shopId");
        return Brand.dao.getBusinessAll(shopId);
    }

    // 获取所有重量单位
    public List<Product.WeightUnit> getAllWeightUnit() {
        List<Product.WeightUnit> allWeightUnit = new ArrayList<Product.WeightUnit>();
        for (Product.WeightUnit weightUnit : Product.WeightUnit.values()) {
            allWeightUnit.add(weightUnit);
        }
        return allWeightUnit;
    }

    // 获取商品分类树
    public List<ProductCategory> getProductCategoryTreeList() {
        shopId=getAttr("shopId");
        return ProductCategory.dao.getBusinessProductCategoryTreeList(shopId);
    }

    public static void main(String[] args) {
        String str="/shop/wmh/product/201712/1512310199942.html";
        System.out.println(str.indexOf("/shop"));
    }


}
